<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      @returnBack="$emit('returnModify')"
    >
      <template v-slot:full-button>
        <el-button @click="save('save')">保存</el-button>
        <el-button @click="save('saveAndCreate')">保存并新增</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-attendDeptNames>
              <el-input
                v-model="formInfo.data.attendDeptNames"
                type="input"
                :disabled="true"
                :class="'not-mongolia'"
                placeholder="请选择参培部门"
              >
                <template #append>
                  <el-icon @click="openUseDeptWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-trainingTime>
              <el-date-picker
                v-model="formInfo.data.trainingTime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                range-separator="至"
                align="right"
                :default-time="[
                  new Date(2000, 1, 1, 0, 0, 0),
                  new Date(2000, 1, 1, 23, 59, 59),
                ]"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              ></el-date-picker>
            </template>
            <template v-slot:form-useDeptUserNames>
              <el-input
                v-model="formInfo.data.useDeptUserNames"
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择使用部门确认人员"
              >
                <template #append>
                  <el-icon @click="openUseUserList"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-manageDeptUserNames>
              <el-input
                v-model="formInfo.data.manageDeptUserNames"
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择管理部门确认人员"
              >
                <template #append>
                  <el-icon @click="openManageUserList"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-assetNames>
              <el-input
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择资产"
                v-model="formInfo.data.assetNames"
              >
                <template #append>
                  <el-icon @click="openEquipmentWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-filePathList>
              <UploadImg
                v-model:value="formInfo.data.filePathList"
                :action="action"
                :limit="5"
                :multiple="true"
                list-type="text"
                title="附件"
                :file-type="fileType"
                :response-fn="handleResponse"
              />
            </template>
          </page-form>
        </div>
      </div>

      <select-dept
        v-if="selectUseDeptInfo.visible"
        v-model:show-dialog="selectUseDeptInfo.visible"
        :query="selectUseDeptInfo.query"
        :checkedList="selectUseDeptInfo.checkedList"
        :check-box="true"
        :highlight-row="true"
        :saveEmpty="true"
        @callback="selectUseDeptCallback"
      />

      <SelectUsers
        v-if="selectUseUserInfo.visible"
        v-model:showDialog="selectUseUserInfo.visible"
        :query="selectUseUserInfo.query"
        :checkedList="selectUseUserInfo.checkedList"
        :api="getRrgUserList"
        :saveEmpty="true"
        :check-box="true"
        :highlight-row="true"
        @callback="selectUseUserCallBack"
      />
      <SelectUsers
        v-if="selectManageUserInfo.visible"
        v-model:showDialog="selectManageUserInfo.visible"
        :query="selectManageUserInfo.query"
        :checkedList="selectManageUserInfo.checkedList"
        :api="getRrgUserList"
        :saveEmpty="true"
        :check-box="true"
        :highlight-row="true"
        @callback="selectManageUserCallBack"
      />
      <Select-asset
        v-if="selectAssetInfo.visible"
        v-model:show-dialog="selectAssetInfo.visible"
        :highlightRow="true"
        :checkBox="true"
        :saveEmpty="true"
        :checkedList="selectAssetInfo.checkedList"
        :query="selectAssetInfo.query"
        :filterInfoList="selectAssetInfo.filterInfoList"
        @callback="callBackAsset"
      />
    </NewFullScreen>
  </div>
</template>

<script setup name="assetDictModify">
import utils from '@/common/js/utils' // 公共方法
import {
  getOperationTrainingRecordById,
  createOperationTrainingRecord,
  updateOperationTrainingRecord,
} from '@/api/quality'
import { getCoreCodeStatus, getUnitAll, getSupplierPage } from '@/api/core'
import { getRrgUserList } from '@/api/base'
import axios from 'axios'
import SelectAsset from '@/components/SelectAsset/selectAsset'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: [String, Number],
  },
  title: {
    type: String,
  },
})
const action = ref(axios.defaults.baseURL + '/pub/uploadfile')
const fileType = ref(['jpg', 'png', 'jpeg', 'pdf'])
const formInfo = reactive({
  ref: null,
  data: {
    trainingType: 1,
  },
  fieldList: [
    {
      label: '培训主题',
      value: 'trainingSubject',
      type: 'input',
      labelTip: '设备/器械名称及数量等信息',
      required: true,
    },
    {
      label: '参培部门',
      value: 'attendDeptNames',
      type: 'slot',
      required: true,
    },
    {
      label: '培训方式',
      value: 'trainingType',
      type: 'select-model',
      code: 'training_type',
      required: true,
    },
    {
      label: '培训时间',
      value: 'trainingTime',
      type: 'slot',
      required: true,
    },
    {
      label: '设备及配套是否齐全',
      value: 'isComplete',
      type: 'select-model',
      code: 'yes_or_no',
      labelTip: '配套包含配套设施，随货清单、使用说明书等',
      required: true,
    },
    {
      label: '使用部门确认人员',
      value: 'useDeptUserNames',
      type: 'slot',
    },
    {
      label: '管理部门确认人员',
      value: 'manageDeptUserNames',
      type: 'slot',
    },
    {
      label: '培训后是否可独立操作使用',
      value: 'canOperation',
      type: 'select-model',
      code: 'yes_or_no',
      required: true,
    },
    {
      label: '参加培训人员',
      value: 'attendUsers',
      type: 'textarea',
      required: true,
    },
    {
      label: '资产',
      value: 'assetNames',
      type: 'slot',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
    {
      label: '附件',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
  ],
  rules: {},
  labelWidth: '120px',
})
const selectUseDeptInfo = reactive({
  visible: false,
  checkedList: [],
  query: {
    // deptAuth: 'id',
  },
})

const selectUseUserInfo = reactive({
  visible: false,
  saveEmpty: true,
  checkedList: [],
  query: {
    hasAllDept: 1,
  },
})
const selectManageUserInfo = reactive({
  visible: false,
  saveEmpty: true,
  checkedList: [],
  query: {
    hasAllDept: 1,
  },
})
const selectAssetInfo = reactive({
  visible: false,
  checkedList: [],
  query: {
    assetSourceAuth: true,
    statusMult: '3,6',
  },
  filterInfoList: [
    {
      type: 'input',
      label: '名称',
      value: 'assetNameLike',
    },
    {
      type: 'input',
      label: '编码',
      value: 'assetCodeLike',
    },
  ],
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
onMounted(() => {
  initRules()
  if (props.id) {
    getDeatil()
  }
})
// 初始化校验规则
function initRules() {
  formInfo.rules = proxy.$initRules(formInfo.fieldList)
  formInfo.rules.supplierPhone = [
    { required: true, message: '请输入供应商电话', trigger: 'blur' },
    { validator: proxy.$validate.cellphone, trigger: 'blur' },
  ]
  formInfo.rules.afterSalePhone = [
    { validator: proxy.$validate.cellphone, trigger: 'blur' },
  ]
}
function getDeatil() {
  getOperationTrainingRecordById(props.id).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data
      formInfo.data = data
      if (formInfo.data.filePath) {
        formInfo.data.filePathList = utils.splitArr(formInfo.data.filePath)
      }
      if (formInfo.data.trainingTimeBegin || formInfo.data.trainingTimeEnd) {
        formInfo.data.trainingTime = [
          formInfo.data.trainingTimeBegin,
          formInfo.data.trainingTimeEnd,
        ]
      }
    }
  })
}
function save(str) {
  formInfo.ref.validate((valid) => {
    if (valid) {
      if (formInfo.data.trainingTime && formInfo.data.trainingTime.length) {
        formInfo.data.trainingTimeBegin = formInfo.data.trainingTime[0]
        formInfo.data.trainingTimeEnd = formInfo.data.trainingTime[1]
      }
      if (formInfo.data.filePathList && formInfo.data.filePathList.length) {
        formInfo.data.filePath = String(formInfo.data.filePathList)
      } else {
        formInfo.data.filePath = ''
      }
      const api = props.id
        ? updateOperationTrainingRecord
        : createOperationTrainingRecord
      api(formInfo.data).then((resp) => {
        if (resp && resp.success) {
          if (str === 'save') {
            //保存
            showDialog.value = false
            emits('returnModify')
          } else if (str === 'saveAndCreate') {
            //保存并新增
            formInfo.data = {}
            emits('update:title', '新增操作培训记录')
          }
        }
      })
    }
  })
}

function openUseDeptWindow() {
  if (formInfo.data.attendDeptIds) {
    if (formInfo.data.attendDeptIds.length === 1) {
      selectUseDeptInfo.checkedList = [Number(formInfo.data.attendDeptIds)]
    } else {
      selectUseDeptInfo.checkedList = formInfo.data.attendDeptIds
        .split(',')
        .map((item) => Number(item))
    }
  } else {
    selectUseDeptInfo.checkedList = []
  }
  selectUseDeptInfo.visible = true
}
function selectUseDeptCallback(row) {
  if (row && row.length) {
    formInfo.data.attendDeptIds = row.map((item) => item.id).toString()
    formInfo.data.attendDeptNames = row.map((item) => item.name).toString()
  } else {
    formInfo.data.attendDeptIds = ''
    formInfo.data.attendDeptNames = ''
  }
}

function openUseUserList() {
  if (formInfo.data.useDeptUserIds) {
    if (formInfo.data.useDeptUserIds.length === 1) {
      selectUseUserInfo.checkedList = [Number(formInfo.data.useDeptUserIds)]
    } else {
      selectUseUserInfo.checkedList = formInfo.data.useDeptUserIds
        .split(',')
        .map((item) => Number(item))
    }
  } else {
    selectUseUserInfo.checkedList = []
  }
  selectUseUserInfo.visible = true
}
function selectUseUserCallBack(row) {
  if (row && row.length) {
    formInfo.data.useDeptUserIds = row.map((item) => item.id).toString()
    formInfo.data.useDeptUserNames = row.map((item) => item.name).toString()
  } else {
    formInfo.data.useDeptUserIds = ''
    formInfo.data.useDeptUserNames = ''
  }
}
function openManageUserList() {
  if (formInfo.data.manageDeptUserIds) {
    if (formInfo.data.manageDeptUserIds.length === 1) {
      selectManageUserInfo.checkedList = [
        Number(formInfo.data.manageDeptUserIds),
      ]
    } else {
      selectManageUserInfo.checkedList = formInfo.data.manageDeptUserIds
        .split(',')
        .map((item) => Number(item))
    }
  } else {
    selectManageUserInfo.checkedList = []
  }
  selectManageUserInfo.visible = true
}
function selectManageUserCallBack(row) {
  if (row && row.length) {
    formInfo.data.manageDeptUserIds = row.map((item) => item.id).toString()
    formInfo.data.manageDeptUserNames = row.map((item) => item.name).toString()
  } else {
    formInfo.data.manageDeptUserIds = ''
    formInfo.data.manageDeptUserNames = ''
  }
}
function openEquipmentWindow() {
  if (formInfo.data.assetIds) {
    if (formInfo.data.assetIds.length === 1) {
      selectAssetInfo.checkedList = [Number(formInfo.data.assetIds)]
    } else {
      selectAssetInfo.checkedList = formInfo.data.assetIds
        .split(',')
        .map((item) => Number(item))
    }
  } else {
    selectAssetInfo.checkedList = []
  }
  selectAssetInfo.visible = true
}
function callBackAsset(data) {
  if (data && data.length) {
    formInfo.data['assetNames'] = data.map((item) => item.assetName).toString()
    formInfo.data['assetIds'] = data.map((item) => item.id).toString()
  } else {
    formInfo.data['assetNames'] = ''
    formInfo.data['assetIds'] = ''
  }
}
function handleResponse(response, file) {
  return response
}
</script>

<style scoped></style>
